package org.jeecg.modules.product.test;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 使用 AtomicInteger 实现多线程计数
 * AtomicInteger 是一个支持原子操作的整数类，适合在高并发场景下使用。
 */
public class CounterWithAtomicInteger {
    private final AtomicInteger count = new AtomicInteger(0);

    public void increment() {
        count.incrementAndGet();  // 原子操作，无需加锁
    }

    public int getCount() {
        return count.get();
    }

    public static void main(String[] args) throws InterruptedException {
        CounterWithAtomicInteger counter = new CounterWithAtomicInteger();

        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        };

        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("Final count: " + counter.getCount()); // 输出应该是2000
    }
}